package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            String line =readLine();

            String[] array = line.split("\\s");

            String method;
            String uri;
            String protocol;

            method = array[0];
            uri = array[1];
            protocol = array[2];

            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);


            Map<String , String> headers = new HashMap<>();
            while (!(line = readLine()).isEmpty()){
                array = line.split(":\\s");
                headers.put(array[0],array[1]);
                System.out.println(line);
            }
            System.out.println(headers);

        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private String readLine() throws IOException {

        InputStream in = socket.getInputStream();

        StringBuilder builder = new StringBuilder();
        int d;
        char pre = 'a', cur = 'a';
        while ((d = in.read())!=-1){
            pre = (char)d;
            if (cur==13&&pre==10){
                break;
            }
            builder.append(pre);
            cur = pre;
        }
        String line = builder.toString().trim();
        return line;
    }
}
